using System;
using System.Collections;
using System.Text;
using System.Web;

namespace Sedna.Core.Controller.Common
{
	/// <summary>
	/// Base action for all server validation actions
	/// </summary>
	public abstract class AbstractValidationAction : AbstractAction
	{
        private const string VALIDATION_VALUE_PATH = "call['validationValue']";
        private const string ERROR_MESSAGE_PATH = "ec['validationErrorMessage']";
        private const string ERROR_MESSAGE_KEYS_PATH = "ec['validationErrorMessageKeys']";
	    
        protected IList messageKeys = new ArrayList();
	    protected bool validateEmpty = false;

	    public bool ValidateEmpty
	    {
	        set { validateEmpty = value; }
	    }

	    public override IActionResult Execute(IExecutionContext executionContext)
		{
            executionContext.CallContext.Result = Validate(executionContext, (string)GetValidationValue(executionContext));
		    return CreateResult(successStatus);
		}
	    
	    protected virtual void SetIsValid(IExecutionContext executionContext, bool value)
	    {
            executionContext.CallContext.Result = value;
	    }
	    
	    protected virtual void SetErrorMessage(IExecutionContext executionContext, string message)
	    {
            executionContext.SetPropertyValue(ERROR_MESSAGE_PATH, message);    
	    }

        protected virtual void SetErrorMessageKey(IExecutionContext executionContext, string messageKey)
        {
            AddErrorMessageKey(messageKey);

            SetErrorMessageKeys(executionContext);
        }

        protected virtual void SetErrorMessageKeys(IExecutionContext executionContext)
        {
            executionContext.SetPropertyValue(ERROR_MESSAGE_KEYS_PATH, messageKeys);
        }
        
	    protected virtual object GetValidationValue(IExecutionContext executionContext)
	    {
            return executionContext.GetPropertyValue(VALIDATION_VALUE_PATH);
	    }
	    
		protected virtual bool Validate(IExecutionContext executionContext, string validationValue)
		{
			return Validate(executionContext);
		}
		protected virtual bool Validate(IExecutionContext executionContext)
		{
			return true;
		}
	    
	    protected bool AddErrorMessageKey(String messageKey)
	    {
	        if (!messageKeys.Contains(messageKey))
	        {
                messageKeys.Add(messageKey);
                return true;
	        }
            return false;
	    }
	    
	    protected void ClearErrorMessageKeys()
	    {
	        messageKeys.Clear();
	    }
	}
}
